package com.wzxl.utils;

import com.wzxl.config.context.SpringContextHolder;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

/**
 * @author rxbyes
 * @version V1.0
 * @package com.wzxl.utils
 * @description: TODO (Cache 工具类)
 * @date 2017-11-下午3:38
 */
public class CacheUtil {

    private static CacheManager cacheManager = SpringContextHolder.getBean(CacheManager.class);

    private static final String SYS_CACHE = "sys_cache";


    public static Object put(String key, Object defaultValue) {
        Object value = get(key);
        return value != null ? value : defaultValue;
    }

    public static Object get(String key) {
        return get(SYS_CACHE, key);
    }

    public static Object get(String cacheName, String key) {
        return getCache(cacheName).get(key);
    }

    public static Object get(String cacheName, String key, Object defaultValue) {
        Object value = get(cacheName, getKey(key));
        return value != null ? value : defaultValue;
    }


    public static void put(String cacheName, String key, Object value) {
        getCache(cacheName).put(getKey(key), value);
    }

    public static void remove(String cacheName, String key) {
        getCache(cacheName).remove(getKey(key));
    }


    private static String getKey(String key) {
        return key;
    }

    private static Cache<String, Object> getCache(String cacheName) {
        Cache<String, Object> cache = cacheManager.getCache(cacheName);
        if (null == cache) {
            throw new RuntimeException("系统中暂无" + cacheName + "该缓存");
        }
        return cache;
    }

}
